package com.airspyar;


import java.util.ArrayList;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class SensorListener implements SensorEventListener {
	private float[] accelerometerValues=null, geomagneticMatrix=null;
	private float []inR, outR;
	private ArrayList<float[]> indicationsList=new ArrayList<float[]>(INDICATIONS_BUFFER_SIZE);
	private final Object indicationsListMutex=new Object();
	private final static int INDICATIONS_BUFFER_SIZE=7;
	
	public SensorListener(){
        inR=new float[16];
        outR=new float[16];
	}
	
	public Vector3d getOrientationVector(){
		Vector3d orientationVector=new Vector3d(0,0,0);
		
		synchronized(indicationsListMutex){
			int size=indicationsList.size();
			if(size==0)
				return null;
			
			for(int i=0;i<size;i++){
		        float x=(float)(Math.cos(indicationsList.get(i)[1])*Math.sin(indicationsList.get(i)[0]));
		        float y=(float)(Math.cos(indicationsList.get(i)[1])*Math.cos(indicationsList.get(i)[0]));
		        float z=-(float)Math.sin(indicationsList.get(i)[1]);
		        
		        orientationVector.add(x, y, z);
			}
		}
		
		return orientationVector;
	}
	
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		
		switch(event.sensor.getType()){
		case Sensor.TYPE_ACCELEROMETER:
			accelerometerValues=event.values.clone();
		break;
		case Sensor.TYPE_MAGNETIC_FIELD:
			geomagneticMatrix=event.values.clone();
		break;
		}
		
		if(accelerometerValues==null || geomagneticMatrix==null)
			return;

        SensorManager.getRotationMatrix(inR, null, accelerometerValues, geomagneticMatrix);
        SensorManager.remapCoordinateSystem(inR, SensorManager.AXIS_X, SensorManager.AXIS_Z, outR); 
        
        float[] orientationValues=new float[3];
        SensorManager.getOrientation(outR, orientationValues);

        synchronized(indicationsListMutex){
        	if(indicationsList.size()>=INDICATIONS_BUFFER_SIZE)
        		indicationsList.remove(0);
        	
        	indicationsList.add(orientationValues);
        }
	}

}
